import { errors } from '@vinejs/vine'
import app from '@adonisjs/core/services/app'
import { HttpContext, ExceptionHandler } from '@adonisjs/core/http'
import { Exception } from '@adonisjs/core/exceptions'
import db from '@adonisjs/lucid/services/db'

export default class HttpExceptionHandler extends ExceptionHandler {
  /**
   * In debug mode, the exception handler will display verbose errors
   * with pretty printed stack traces.
   */
  protected debug = !app.inProduction

  protected ignoreCodes: string[] = ['']
  protected ignoreStatuses: number[] = [404, 422, 403, 401]

  protected context(ctx: HttpContext) {
    return {
      requestId: ctx.request.id,
      userId: ctx.auth?.user?.id,
      ip: ctx.request.ip(),
    }
  }

  /**
   * The method is used for handling errors and returning
   * response to the client
   */
  async handle(error: unknown, ctx: HttpContext) {
    ctx.response.type('.json')

    if (error instanceof Exception) {
      ctx.response.ok({
        code: error.status,
        message: error.message,
      })
    } else if (error instanceof errors.E_VALIDATION_ERROR) {
      ctx.response.ok({
        code: error.status,
        message: error.code,
        data: error.messages,
      })
    } else {
      const { status, message, code, ...restData } = error as any
      ctx.response.ok({
        code: status,
        message: message || code,
        data: restData,
      })
    }

    // return super.handle(error, ctx)
  }

  /**
   * The method is used to report error to the logging service or
   * the a third party error monitoring service.
   *
   * @note You should not attempt to send a response from this method.
   */
  async report(error: unknown, ctx: HttpContext) {
    return super.report(error, ctx)
  }
}
